package org.squabble.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.squabble.domain.Account;

public class LoginService extends TokenBasedRememberMeServices {

	@Autowired
	AccountService accountService;

	protected String key;
	
	@Override
	public void onLoginSuccess(HttpServletRequest request,
			HttpServletResponse response,
			Authentication successfulAuthentication) {
		Account account = (Account) successfulAuthentication.getPrincipal();
		request.getSession().setAttribute("account", account);
		accountService.updateLastLogin(account.getId());
		super.onLoginSuccess(request, response, successfulAuthentication);
	}

	@Override
	public UserDetails processAutoLoginCookie(String[] cookieTokens,
			HttpServletRequest request, HttpServletResponse response) {
		UserDetails userDetails = super.processAutoLoginCookie(cookieTokens,
				request, response);
		request.getSession().setAttribute("account", (Account) userDetails);
		return userDetails;
	}

	public void updateCookie(HttpServletRequest request,
			HttpServletResponse response, UserDetails user) {
		RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken(
				this.getKey(), user, user.getAuthorities());
		super.onLoginSuccess(request, response, auth);
	}

}
